<template>
     <!-- 操作按钮区 -->
    <div class="action-buttons">
      <el-button type="primary" @click="batchSaveDetails">添加</el-button>
      <el-button type="primary" @click="GetBYIdProductionPlanning(scope.row.pickingId)">编辑</el-button>
      <el-button @click="handleImport">导入</el-button>
    </div>
    
    <div>
        <!-- 查询条件部分 -->
       <div class="search-section">
            <el-form :inline="true" :model="prolist">
                <el-form-item label="关联项目">
                    <el-input v-model="prolist.RelatedProject" placeholder="输入关联项目"></el-input>
                </el-form-item>
                <el-form-item label="领料编号">
                    <el-input v-model="prolist.DocumentSubject" placeholder="输入领料编号"></el-input>
                </el-form-item>
                <el-form-item label="领料主题">
                    <el-input v-model="prolist.DocumentNo" placeholder="输入领料主题"></el-input>
                </el-form-item>
                <el-form-item label="领料日期">
                    <el-date-picker v-model="prolist.PickingDate" type="date" placeholder="选择日期"></el-date-picker>-
                    <el-date-picker v-model="prolist.PickingDate" type="date" placeholder="选择日期"></el-date-picker>
                </el-form-item>
                 <el-form-item label="添加人员">
                    <el-input v-model="prolist.ProduceName" placeholder="输入添加人员"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button @click="ShowMaterials">查询</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="page-title">
            <h2>生产领料列表</h2>
        </div>
        <!-- 生产计划列表（仅展示序号列相关结构） -->
        <div class="table-container">
         
            <el-table :data="planList" stripe ref="tableRef" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection"></el-table-column>
                <el-table-column prop="pickingId" label="序号"></el-table-column>
                <el-table-column prop="documentSubject" label="单据主题"></el-table-column>
                <el-table-column prop="documentNo" label="单据编号"></el-table-column>
                <el-table-column prop="pickingDate" label="领料日期">
                     <template #default="scope">
                    {{ formatDate(scope.row.pickingDate) }}
                    </template>
                </el-table-column>
                <el-table-column prop="documentType" label="来源数据类型"></el-table-column>
                <el-table-column prop="documentSource" label="来源单据"></el-table-column>
                <el-table-column prop="pickingNumber" label="领料数量合计"></el-table-column>
                <el-table-column prop="produceDate" label="制单日期">
                     <template #default="scope">
                    {{ formatDate(scope.row.produceDate) }}
                    </template>
                </el-table-column>
                <el-table-column prop="produceName" label="制单人员"></el-table-column>
                <el-table-column prop="relatedProject" label="关联项目"></el-table-column>
                <el-table-column prop="pickingNote" label="备注"></el-table-column>
                
                    <el-table-column prop="right" label="操作">
                    <template #default="scope">
                        <el-button type="text" @click="GetBYIdProductionPlanning(scope.row.pickingId)">编辑</el-button>
                        <el-button  type="text" @click="DeleteProductionPlanning(scope.row.pickingId)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
           <!-- 分页部分 -->

        
             <!-- <el-button @click="batchDelete">批量删除</el-button> -->
        </div>
         <div style="margin-top: 20px">
            <el-pagination
                v-model:current-page="page.pageindex"
                v-model:page-size="page.pageSize"
                :page-sizes="[5, 20, 25, 30]"
                :background="true"
                prev-text="上一页"
                next-text="下一页"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total.totalCount"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { Materialread, Materialwrite } from '@/axios/axiosHelper';
import { ElMessage, ElMessageBox } from 'element-plus';
import router from '@/router';
import axios from 'axios';

// 定义搜索表单数据
const prolist = ref({
    RelatedProject:'',
    DocumentSubject:'',
    DocumentNo:'',
    PickingDate:'',
    ProduceName:'',
});

// 定义分页总数
const total = ref({
  totalCount: 0,
  pageCount:0,
});
// 定义分页对象
const page = ref({
    pageindex: 1,
    pageSize: 15,
});
const formatDate = (dateStr) => {
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
};
// 模拟生产计划列表数据
const planList = ref([
    {
       "pickingId": 0,
        "documentSubject": "",
        "documentNo": "",
        "pickingDate": "",
        "documentType": "",
        "documentSource": "",
        "pickingNumber": '',
        "produceDate": "",
        "produceName": "",
        "relatedProject": "",
        "pickingNote": "",
    }
]);

// 表格引用
const tableRef = ref(null);

// 全选状态
const allChecked = ref(false);
// 选中的 ID 列表
const checkedIds = ref([]);

const ShowMaterials = () => {
//  console.log("ShowMaterials");
Materialread.get("/l-read/api/GetValues/GetMaterialsPicking", {
        params: {
            pageindex: page.value.pageindex,
            pageSize: page.value.pageSize,
            RelatedProject: prolist.value.RelatedProject,
            DocumentSubject: prolist.value.DocumentSubject,
            DocumentNo: prolist.value.DocumentNo,
            PickingDate: prolist.value.PickingDate,
            ProduceName: prolist.value.ProduceName,
        }
    }).then((res) => {
        planList.value = res.data.data.result;
        console.log("显示数据",res.data.data);

        total.value.totalCount = res.data.data.totalCount;
        total.value.pageCount = res.data.data.pageCount;
        // 重置全选状态和选中的 ID 列表
        allChecked.value = false;
        checkedIds.value = [];
        console.log(res.data.data);
    }).catch((error) => {
        console.error('接口请求失败:', error);
        ElMessage.error('数据获取失败，请稍后重试');
    });
};


// 编辑跳转修改
const GetBYIdProductionPlanning = (pickingId) => {
    router.push({
        name: 'FTPicking',
        query: {
            pickingId: pickingId
        }
    }).catch((error) => {
        console.error('路由跳转错误:', error);
        ElMessage.error('跳转失败，请检查');
    });
    console.log(pickingId);
};






const batchSaveDetails = ()=>{

   router.push("/AddMaterialsPicking");
}
// 导入
const handleImport = () => {
  Materialread.get("/l-read/api/GetValues/ExportToExce2").then((res)=>{
    ElMessage.success('导入成功');
  })
};
// 单个删除功能
// 删除单条记录
const DeleteProductionPlanning = async (pickingId) => {
    try {
        const confirmResult = await ElMessageBox.confirm(
            '确认删除该条记录？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        if (confirmResult === 'confirm') {
            const response = await Materialwrite.delete(
                `/l-wirth/api/Ment/AddMaterialsPicking`,
                {
                    params: { pickingId: pickingId.toString() }
                }
            );
            if (response.data.code === 300) {
                ElMessage.success('删除成功');
                ShowMaterials(); // 调用 ShowMaterials 方法刷新数据
            } else {
                ElMessage.error(`删除失败：${response.data.message}`);
            }
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除错误:', error);
            ElMessage.error('删除失败，请检查网络或联系管理员');
        }
    }
};




const handleSizeChange = (val) => {
    page.value.PageSize = val;
    ShowMaterials();
};
const handleCurrentChange = (val) => {
    page.value.PageIndex = val;
    ShowMaterials();
};
onMounted(() => {
    ShowMaterials();
})
</script>

<style scoped>
.search-section {
    margin-bottom: 20px;
}

.table-container {
    max-height: 400px; /* 固定表格最大高度 */
    overflow-y: auto; /* 超出高度显示滚动条 */
    margin-bottom: 20px; /* 为分页预留空间 */
}

.el-table {
    width: 100%; /* 表格宽度占满容器 */
}
</style>    